package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.pojo.TbSpecification;
import com.dongdongshop.service.EsService;
import com.dongdongshop.util.PageBean;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @ClassName EsServiceImpl
 * @Author RC
 * @date 2021.01.01 21:58
 */
@Component
@Service
public class EsServiceImpl implements EsService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    private static final Logger logger = (Logger) LoggerFactory.getLogger(EsServiceImpl.class);

    @Override
    public void addSource(List<TbItem> itemList) throws IOException {
        /*// 1、创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("item_index");
        // 2、客户端执行请求 IndicesClient，请求后获得相应
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        logger.info(createIndexResponse+"");*/
        for (TbItem item : itemList) {
            IndexRequest indexRequest = new IndexRequest("item_index").source(JSON.toJSONString(item),XContentType.JSON);
            // 执行得到 response
            IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            logger.info("出参：" + indexResponse.toString());
        }

    }

    @Override
    public PageBean<TbItem> getInfoBySearch(String search, Integer pageNumber, Integer pageSize)  {
        // 搜索请求对象
        SearchRequest searchRequest = new SearchRequest("item_index");

        // 搜索源构建对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 页码
        if (pageNumber == null || pageNumber < 0) {
            pageNumber = 0;
        }
        // 页数
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        PageBean<TbItem> page = new PageBean<>();
        page.setPageNumber(pageNumber);
        page.setPageSize(pageSize);
        /*int page = pageNumber; // 页码
        int size = pageSize; // 每页显示的条数
        int index = (page - 1) * size;*/
        searchSourceBuilder.from(page.getStartIndex());
        searchSourceBuilder.size(page.getPageSize());

        // 搜索方式
        // Query-match单字段模糊查询
        searchSourceBuilder.query( QueryBuilders.matchQuery("title", search));
        //SearchSourceBuilder totalHits = searchSourceBuilder.trackTotalHits(true);
//        int count = Integer.parseInt(String.valueOf(totalHits));

        // 设置源字段过虑,第一个参数结果集包括哪些字段，第二个参数表示结果集不包括哪些字段
       // searchSourceBuilder.fetchSource(new String[]{"name", "doubanScore", "actorList"}, new String[]{});
        // 向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);

        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置高亮前缀
        highlightBuilder.preTags("<span style='color:red' >");
        //设置高亮字段
        highlightBuilder.field("title");
        //设置高亮后缀
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);



        // 执行搜索,向ES发起http请求
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 搜索结果
        SearchHits hits = searchResponse.getHits();
        long value = hits.getTotalHits().value;
        //总条数
        int count = Integer.valueOf((int) value).intValue();
        List<TbItem> itemList = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            // 文档的主键
            String id = hit.getId();

            // 源文档内容
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            String title = (String) sourceAsMap.get("title");
            TbItem item = JSON.parseObject(JSON.toJSONString(sourceAsMap), TbItem.class);
            // 获取高亮查询的内容。如果存在，则替换原来的name
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if( highlightFields != null ){
                HighlightField nameField = highlightFields.get("title");
                if(nameField!=null){
                    Text[] fragments = nameField.getFragments();
                    StringBuilder stringBuilder = new StringBuilder();
                    for (Text str : fragments) {
                        //拼接高亮字段 前缀后缀 及search值
                        stringBuilder.append(str.string());
                    }
                    title = stringBuilder.toString();
                    item.setTitle(title);
                }
            }
            //item.setId((long) Integer.parseInt(hit.getId()));
            itemList.add(item);
        }

      //return itemList;

        page.setTotalCount(count);
        page.setResult(itemList);
        return page;
    }
}
